package com.innovamed.websocket.utils.server;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Copyright: Copyright (c) Jun_Zhou @PackageName:com.innovamed.websocket.utils.server @Description:
 * 本机服务器相关的工具类;
 *
 * @version: v1.0.0
 * @author: JunZhou @Email: 1769676159@qq.com @Site: CERNO
 * @date: 2019/8/25 21:33
 */
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
  private int serverPort;

  public int getServerPort()
  {
    return serverPort;
  }

  public String getUrl()
  {
    InetAddress address = null;
    try {
      address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return "http://" + address.getHostAddress() + ":" + this.serverPort;
  }

  public String getHost()
  {
    InetAddress address = null;
    try {
      address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
    return address.getHostAddress();
  }

  @Override
  public void onApplicationEvent(WebServerInitializedEvent event)
  {
    serverPort = event.getWebServer().getPort();
  }

}
